package org.lansir.af.reminder;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.lansir.af.database.DataRowActivity;
import org.lansir.af.database.Database;
import org.lansir.af.dataview.DataViewActivity;
import org.lansir.af.dataview.DataViewItem;
import org.lansir.af.dataview.DataViewItemActivity;
import org.lansir.af.ui.CommonActivity;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * 闹钟数据
 * @author 蓝智宏
 *
 */
public class DataViewAlarm {

	private final String sActivityQuery = "select * from "
			+ Database.sTableNameAlarms + " where ActivityID=%d";
	private DataViewItemActivity dataViewItemActivity;

	protected String sTableName = "";
	// fields
	protected Context ctx = null;
	protected Database db = null;
	
	private final int dayType = CommonActivity.ViewType.TODAY_ALARM;
	
	// fields
	private DataViewActivity dataViewActivity = null;
	
	private List<DataViewItemActivity> dataViewItemAlarms = new ArrayList<DataViewItemActivity>();
	private List<DataViewItemActivity> dataViewItemActivities = new ArrayList<DataViewItemActivity>();
	private AlarmItemsComparator fnAlarmsItemsCmp = null;
	private Calendar calStartDate = Calendar.getInstance();

	// Comparator type for appointments
	public class AlarmItemsComparator implements Comparator<DataViewItemActivity> {
		@Override
		public int compare(DataViewItemActivity item1, DataViewItemActivity item2) {

			// today items for sorting
			if (item1.getTimeAsSeconds() == item2.getTimeAsSeconds()) {
				String s1 = item1.getSubject();
				String s2 = item2.getSubject();
				return s1.compareTo(s2);
			} else {

				if (item1.getTimeAsSeconds() > item2.getTimeAsSeconds())
					return 1;
				if (item1.getTimeAsSeconds() < item2.getTimeAsSeconds())
					return -1;

				if (item1.getTimeAsSeconds() == item2.getTimeAsSeconds()) {
					String s1 = item1.getSubject();
					String s2 = item2.getSubject();
					return s1.compareTo(s2);
				}
			}

			return 0;
		}
	};
	
	public DataViewAlarm(Context ctx, Database db) {
		this.ctx = ctx;
		this.db = db;
		sTableName = Database.sTableNameAlarms;

		// create alarsm manager instance
		//alarmsManager = new AlarmsManager(this.db, this.prefs);

		this.fnAlarmsItemsCmp = new AlarmItemsComparator();

		dataViewActivity = new DataViewActivity(db);
		
	}
	
	private boolean reloadData() {
		if (db.databaseReady()) {
			dataViewActivity.reloadTable();

			dataViewActivity.filterData(calStartDate, dayType);
			dataViewItemActivities = dataViewActivity.getAppointlistForAlarm(calStartDate);
			return true;
		}

		return false;
	}
	
	public boolean collectAlarmItems() {
		calStartDate.setTimeInMillis(System.currentTimeMillis());

		final int iHour = calStartDate.get(Calendar.HOUR_OF_DAY);
		final int iMinute = calStartDate.get(Calendar.MINUTE);
		final int iCurrTimeKey = (iHour * 100) + iMinute;

		dataViewItemAlarms.clear();

		if (reloadData()) {

			//Log.v("LAN_DEBUG",">>collect appointments");
			// collect appointments
			for (int i = 0; i < dataViewItemActivities.size(); i++) {
				DataViewItemActivity row = dataViewItemActivities.get(i);
				//Log.v("LAN_DEBUG", row.sSubject);
				//如果在Appt或者Task中有选择闹铃，那么进行下列处理
				if ((row != null) && (row.isAlarm())) {
					//检查时间是否过期
					if (row.timeOverdue(iCurrTimeKey)) {
						dataViewItemAlarms.add(row);
						/*if (alarmsManager.CanShowAlarmToday(
								AlarmDataViewItem.iOrderAppts, row.lID, row
										.IsRepeat())) {
							AlarmDataViewItem item = new AlarmDataViewItem(
									row.lID, row.sSubject,
									AlarmDataViewItem.iOrderAppts, row.bAlarm, row.iRingerMode);
							item.SetRepeatDays(row.GetVisibleDays());
							item.Set(row.GetStartHour(), row.GetStartMinute(),
									row.GetDuration());
							alarmItemsAppts.add(item);
						}*/
					}
				}
			}
			Collections.sort(dataViewItemAlarms, fnAlarmsItemsCmp);
			Log.v("ActivityFairy", "DataViewItemAlarms count:" + dataViewItemAlarms.size());
			return true;
		}
		return false;
	}


	protected void filterDataForView(DataViewItem item, Calendar calStartDate,
			int iDayType) {

	}

	protected void filterDataPrepare(Calendar calStartDate, int iDayType) {

	}

	protected void sortView() {

	}

	public Database.Result getDataViewItemActivity(int iActivityID) {

		Database.Result result = Database.Result.errUnknown;
		String sql = String.format(sActivityQuery, iActivityID);
		SQLiteDatabase sqldb = db.getSQLiteDb();
		Cursor cr = sqldb.rawQuery(sql, null);
		if (cr == null) {
			result = Database.Result.errCantGetData;
		} else {
			if (cr.getCount() > 0) {
				cr.moveToFirst();
				setActivityItem(cr);
			} else {
				result = Database.Result.errCantFindData;
			}
		}
		cr.close();
		return result;
	}

	private void setActivityItem(Cursor cr) {

		dataViewItemActivity.setID(cr.getLong(DataRowActivity.fid.ID));
		dataViewItemActivity.setSubject(cr
				.getString(DataRowActivity.fid.Subject));
		dataViewItemActivity.setLocation(cr
				.getString(DataRowActivity.fid.Location));
		dataViewItemActivity.setStartDate(calStartDate, cr
				.getLong(DataRowActivity.fid.StartDate));
		dataViewItemActivity
				.setAlarm(cr.getLong(DataRowActivity.fid.Alarm) == 1);

		dataViewItemActivity.setRepeatType(cr
				.getInt(DataRowActivity.fid.RepeatType));
		dataViewItemActivity.setRingerMode(cr
				.getInt(DataRowActivity.fid.RingerMode));

		if (!cr.isNull(DataRowActivity.fid.RepeatEvery))
			dataViewItemActivity.setRepeatEvery(cr
					.getInt(DataRowActivity.fid.RepeatEvery));

		if (!cr.isNull(DataRowActivity.fid.RepeatEndOnDate))
			dataViewItemActivity.setRepeatEndOnDate(cr
					.getLong(DataRowActivity.fid.RepeatEndOnDate));
		Log.v("ActivityFairy", "Subject:" + dataViewItemActivity.getSubject());
	}

	public DataViewItemActivity getDataViewItemActivity() {
		return dataViewItemActivity;
	}

	public void setDataViewItemActivity(
			DataViewItemActivity dataViewItemActivity) {
		this.dataViewItemActivity = dataViewItemActivity;
	}

	public List<DataViewItemActivity> getDataViewItemAlarms() {
		return dataViewItemAlarms;
	}

	public void setDataViewItemAlarms(List<DataViewItemActivity> dataViewItemAlarms) {
		this.dataViewItemAlarms = dataViewItemAlarms;
	}

}
